<template>
  <view>
    <view class="search-view">
      <u-search
        @custom="searchData()"
        @search="searchData()"
        @clear="searchData()"
        action-text="搜索"
        :clearabled="true"
        placeholder="商品名称/编码/条码"
        v-model="keyword"
      ></u-search>
    </view>
    <view class="main-view clearfix">
      <view class="left-view float_left">
        <scroll-view scroll-y="true" class="left-scroll">
          <view
            class="cate-li"
            :class="[!category_id ? 'cate-on' : '']"
            @click="changeCate(0)"
            >全部</view
          >
          <view
            class="cate-li"
            v-for="(item, index) in category_list"
            :key="index"
            @click="changeCate(item.id)"
            :class="[category_id === item.id ? 'cate-on' : '']"
          >
            {{ item.title }}
          </view>
        </scroll-view>
      </view>
      <view class="rigth-view float_left">
        <scroll-view
          scroll-y="true"
          class="rigth-scroll"
          :scroll-top="scrollTop"
          @scrolltolower="scrolltolower"
        >
          <view
            class="goods-li"
            v-for="(item, index) in goods_list"
            :key="index"
          >
            <view class="add-btn">
              <text
                v-if="item.buyNum === 0"
                @click="addGoods(index)"
                class="custom-icon custom-icon-xinzeng"
              ></text>
              <u-number-box
                v-else
                :min="0"
                :index="index"
                @change="buyNumChange"
                :value="item.buyNum"
              ></u-number-box>
            </view>
            <view class="goods-main clearfix">
              <image
                class="goods-img float_left"
                :src="item.images[0]"
                mode="aspectFill"
              ></image>
              <view class="goods-info float_left">
                <view class="goods-name ellipsis">{{ item.title }}</view>
                <view class="goods-code">{{ item.code }}</view>
                <view class="goods-code">
                  {{ item.unitName }};
                  <text v-for="(sku, skuI) in item.specGroup" :key="skuI"
                    >{{ sku.specValueName }};</text
                  >
                </view>
                <view class="goods-num">
                  <text>库存 {{ Number(item.inventory) }}</text>
                  <text>价格 ¥{{ item.salePrice }}</text>
                </view>
                <view class="goods-tag"
                  ><u-tag
                    class="tag-li"
                    mode="plain"
                    size="mini"
                    :text="item.categoryName"
                /></view>
              </view>
            </view>
          </view>
          <u-loadmore :status="load_status" />
        </scroll-view>
      </view>
    </view>
    <view class="bottom-view clearfix">
      <view class="float_left" @click="openPop">
        <view class="shop-icon-view"
          ><u-icon
            name="shopping-cart-fill"
            class="uicon"
            color="#ffffff"
            size="40"
          ></u-icon
        ></view>
        <text>共{{ add_goods.length }}个商品</text>
      </view>
      <view class="float_right"
        ><u-button type="primary" size="medium" @click="addGoodsTo"
          >选好了</u-button
        ></view
      >
    </view>
    <u-popup v-model="sel_pop" mode="bottom">
      <view class="sel-goods-pop">
        <view class="pop-tit clearfix">
          <view class="float_left">本次已选商品</view>
          <view class="float_right" @click="clearGoods">
            <text class="custom-icon custom-icon-shanchu"></text>
            <text>清空</text>
          </view>
        </view>
        <scroll-view class="goods-ul" scroll-y>
          <view
            class="goods-li"
            v-for="(item, index) in add_goods"
            :key="index"
          >
            <view class="goods-name">{{ item.title }}</view>
            <view class="goods-code clearfix">{{ item.code }}</view>
            <view class="goods-code clearfix">
              <view class="float_left">
                {{ item.unitName }};
                <text v-for="(sku, skuI) in item.specGroup" :key="skuI"
                  >{{ sku.specValueName }};</text
                >
              </view>
              <view class="float_right" v-if="item.isEq === 4"
                ><u-number-box
                  :min="0"
                  :index="index"
                  @change="addBuyNumChange"
                  :value="item.buyNum"
                ></u-number-box
              ></view>
              <view class="float_right" v-else>
                <view class="price-input-view" style="margin-bottom: 10rpx">
                  填写数量：
                  <input
                    class="price-input"
                    type="digit"
                    v-model="item.buyNum"
                  />
                </view>
                <view class="price-input-view">
                  其他单位：
                  <input
                    class="price-input"
                    type="digit"
                    v-model="item.otherNum"
                  />
                </view>
              </view>
            </view>
            <text
              class="custom-icon custom-icon-shanchu"
              @click="delGoods(index)"
            ></text>
          </view>
          <view style="padding-top: 100rpx" v-if="!add_goods.length"
            ><u-empty text="未选择商品" mode="data"></u-empty
          ></view>
        </scroll-view>
        <view class="btn-view" @click="addGoodsTo">选好了</view>
      </view>
    </u-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      sel_pop: false, //已选商品
      load_status: "nomore",
      activeName: "all",
      keyword: "",
      is_more: false,
      page: 1,
      pageSize: 10,
      total: 0,
      category_list: [], // 分类列表
      category_id: "", // 分类id
      auditStatus: 2, // 审核状态
      goods_list: [],
      add_goods: [],
      sel_goods_id: [],
      goods_detail: {},
      userCenterId: "",
      isRevealSku: 4, // 5 只显示基本单位 4:主辅助单位都显示
      shopId: "",
      scrollTop: -1,
    };
  },
  onLoad(options) {
    if (options.userCenterId) {
      this.userCenterId = options.userCenterId;
    }
    if (options.shopId) {
      this.shopId = options.shopId;
    }
    const orderGoodsStr = uni.getStorageSync("orderGoods");
    this.add_goods = orderGoodsStr ? JSON.parse(orderGoodsStr) : [];
    this.getAllCategory();
    this.getAllGoodsBySku();
  },

  methods: {
    clearGoods() {
      this.add_goods = [];
    },
    openPop() {
      this.sel_pop = true;
    },
    addGoodsTo() {
      let arr = [];
      let isEqMore = false;

      for (let i in this.add_goods) {
        const item = this.add_goods[i];
        if (item.isEq === 5) {
          if (arr.find((fin) => fin.id === item.id)) {
            this.$u.toast("抄码商品只能选择一个单位进行下单，请重新勾选");
            isEqMore = true;
            break;
          } else {
            arr.push(item);
          }
        }
      }
      if (isEqMore) {
        return;
      }

      this._prePage().goodsData = this.add_goods;
      uni.navigateBack();
    },
    // 滚动到底部，触发上拉加载
    scrolltolower() {
      if (this.total / this.pageSize > this.page) {
        this.page += 1;
        this.getAllGoodsBySku();
      }
    },
    buyNumChange({ value, index }) {
      let target = this.$u.deepClone(this.goods_list);
      target[index].buyNum = value;
      let addGoods = this.$u.deepClone(this.add_goods);
      const goodsI = addGoods.findIndex(
        (item) => item.skuId === target[index].skuId
      );
      if (!Number(value)) {
        addGoods.splice(goodsI, 1);
      } else {
        addGoods[goodsI].buyNum = value;
      }
      this.add_goods = addGoods;
      this.goods_list = target;
    },
    addBuyNumChange({ value, index }) {
      let target = this.$u.deepClone(this.goods_list);
      let addGoods = this.$u.deepClone(this.add_goods);
      const goodsI = target.findIndex(
        (item) => item.skuId === addGoods[index].skuId
      );
      if (!Number(value)) {
        addGoods.splice(goodsI, 1);
      } else {
        addGoods[index].buyNum = value;
      }
      if (goodsI > -1) {
        target[goodsI].buyNum = value;
      }
      this.add_goods = addGoods;
      this.goods_list = target;
    },
    delGoods(index) {
      let target = this.$u.deepClone(this.goods_list);
      const goodsI = target.findIndex(
        (item) => item.skuId === this.add_goods[index].skuId
      );
      if (goodsI > -1) {
        target[goodsI].buyNum = 0;
      }
      this.goods_list = target;
      this.add_goods.splice(index, 1);
    },
    // 获取商品列表
    getAllGoodsBySku() {
      this.load_status = "loading";
      this.$u.api
        .getAllGoodsBySku({
          page: this.page,
          pageSize: this.pageSize,
          isRevealSku: this.isRevealSku,
          keyword: this.keyword,
          userCenterId: this.userCenterId,
          categoryId: this.category_id,
          shopId: this.shopId ? [this.shopId] : "",
        })
        .then((res) => {
          const list = res.data.map((item) => {
            const goods = this.add_goods.find(
              (agoods) => agoods.skuId === item.skuId
            );
            return {
              ...item,
              buyNum: goods ? goods.buyNum : 0,
            };
          });
          if (this.page === 1) {
            this.goods_list = list;
          } else {
            this.goods_list = this.goods_list.concat(list);
          }
          this.total = res.pageTotal;
          this.load_status = this.$utils.loadStatus(
            this.page,
            this.pageSize,
            this.total
          );
        });
    },
    //  获取所有商品分类
    getAllCategory() {
      this.$u.api
        .getAllCategory({
          enableStatus: 5,
        })
        .then((res) => {
          this.category_list = res.data;
        });
    },
    // 切换分类
    changeCate(id) {
      this.scrollTop = 0;
      this.$nextTick(() => {
        this.scrollTop = -1;
      });
      this.category_id = id;
      this.searchData();
    },
    searchData() {
      this.page = 1;
      this.getAllGoodsBySku();
    },
    addGoods(index) {
      const target = this.$u.deepClone(this.goods_list);
      const isindex = this.add_goods.findIndex(
        (item) => item.skuId === target[index].skuId
      );
      if (isindex === -1) {
        target[index].buyNum = 1;
        this.add_goods.push({
          ...target[index],
          otherNum: "",
        });
      } else {
        this.add_goods[isindex].buyNum += target[index].buyNum;
      }
      this.goods_list = target;
    },
  },
};
</script>

<style scoped lang="scss">
.bottom-view {
  box-shadow: 0px 2px 12rpx rgba(0, 0, 0, 0.2);
  position: fixed;
  width: 100%;
  padding: 20rpx;
  bottom: 0;
  left: 0;
  background-color: #ffffff;

  .float_left {
    line-height: 70rpx;

    .shop-icon-view {
      display: inline-block;
      width: 60rpx;
      height: 60rpx;
      border-radius: 100%;
      background-color: $uni-color-primary;
      text-align: center;
      line-height: 60rpx;
      vertical-align: middle;
      margin-right: 20rpx;

      .uicon {
        display: inline-block;
        margin-top: 6rpx;
      }
    }
  }
}

.search-view {
  background-color: #ffffff;
  padding: 20rpx;
  .input-view {
    padding: 0 24rpx;
    input {
      height: 60rpx;
      line-height: 60rpx;
      padding: 0 24rpx;
      margin: 0 auto;
      width: 620rpx;
      border: 1px solid #f5f5f5;
      vertical-align: middle;
      border-radius: 8rpx;
      background-color: #f7f8fa;
    }
  }

  .search-other {
    display: flex;
    border-bottom: 1px solid #f5f5f5;

    .search-li {
      flex: 2;
      text-align: center;
      font-size: 24rpx;
      line-height: 80rpx;

      .arrow-down {
        margin-left: 10rpx;
      }
    }
  }
}

.main-view {
  .left-view {
    width: 168rpx;
    background-color: #f7f8fa;

    .left-scroll {
      width: 100%;
      height: calc(100vh - 214rpx);

      .cate-li {
        line-height: 90rpx;
        padding-left: 36rpx;
        color: #666666;
      }

      .cate-on {
        background-color: #ffffff;
        color: #000000;
        position: relative;

        &::before {
          content: "";
          display: block;
          width: 6rpx;
          height: 20rpx;
          background-color: $uni-color-primary;
          position: absolute;
          left: 14rpx;
          top: 50%;
          transform: translateY(-50%);
        }
      }
    }
  }

  .rigth-view {
    width: calc(100% - 168rpx);
    background-color: #ffffff;

    .rigth-scroll {
      width: 100%;
      height: calc(100vh - 214rpx);

      .goods-li {
        padding: 20rpx;
        border-bottom: 1px solid #f5f5f5;
        position: relative;

        .add-btn {
          position: absolute;
          right: 20rpx;
          bottom: 20rpx;
          .custom-icon {
            color: #ffffff;
            font-size: 32rpx;
            display: block;
            width: 46rpx;
            height: 46rpx;
            text-align: center;
            line-height: 46rpx;
            background-color: $uni-color-primary;
            border-radius: 100%;
          }
        }
        .add-on {
          background-color: #999999;
        }

        .goods-main {
          .goods-img {
            border-radius: 10rpx;
            width: 156rpx;
            height: 156rpx;
            margin-right: 20rpx;
          }

          .goods-info {
            width: 366rpx;

            .goods-name {
              -webkit-line-clamp: 1;
            }

            .goods-code {
              font-size: 24rpx;
              padding-top: 6rpx;
            }

            .goods-tag {
              padding: 10rpx 0;

              .tag-li {
                margin-right: 14rpx;
              }
            }

            .goods-num {
              color: #999999;
              font-size: 22rpx;

              text {
                padding-right: 10rpx;
              }
            }
          }
        }
      }
    }
  }
}
.sel-goods-pop {
  padding-bottom: 1px;
  .pop-tit {
    line-height: 70rpx;
    background-color: #f5f5f5;
    padding: 0 24rpx;
    .float_right {
      font-size: 24rpx;
      color: #666666;
      .custom-icon-shanchu {
        font-size: 26rpx;
        margin-right: 10rpx;
      }
    }
  }
  .goods-ul {
    min-height: 400rpx;
    max-height: 600rpx;
    .goods-li {
      padding: 24rpx;
      position: relative;
      border-bottom: 1px solid #f5f5f5;
      .price-input-view {
        text-align: right;
        .price-input {
          text-align: center;
          width: 150rpx;
          height: 50rpx;
          display: inline-block;
          vertical-align: middle;
          margin-right: 10rpx;
          transform: translateY(-4rpx);
          font-size: 24rpx;
          border: 1px solid #eeeeee;
          border-radius: 8rpx;
        }
      }

      .goods-name {
        width: 660rpx;
      }
      .goods-code {
        padding-top: 10rpx;
        font-size: 24rpx;
        color: #999999;
      }
      .custom-icon-shanchu {
        position: absolute;
        right: 24rpx;
        top: 24rpx;
        width: 40rpx;
        height: 40rpx;
        color: $uni-color-error;
      }
    }
  }
  .btn-view {
    width: 680rpx;
    height: 70rpx;
    line-height: 70rpx;
    border-radius: 10rpx;
    background-color: $uni-color-primary;
    color: #ffffff;
    text-align: center;
    margin: 20rpx auto;
  }
}
</style>
